<?php

/**
 * Protect against register_globals vulnerabilities.
 * This line must be present before any global variable is referenced.
 */
if( !defined( 'MEDIAWIKI' ) ) {
	echo( "This is an extension to the MediaWiki package and cannot be run standalone.\n" );
	die( -1 );
}

class SMW_PropertiesParser{

    public $preg = '/\{\{#property\:(.*?)\|(.*?)\|(.*?)\}\}/';
    
    public static function RegisterHook(&$chain){
        $chain['property'] = array(0,'property');
        return true;
    }
    
    /**
    *   The spected format for properties declaration:
    *       {{#property:hasName|value|[required|optional]}}
    */
    public static function Parse($parser, $name, $type, $required = 'optional'){    
        $t = Title::newFromText("Property:$name");
        $link = $t->getFullURL();
        $output = <<<EOT
<dl class="SMWP_properties_list">
    <dt class="SMWP_property">Property:</dt>
        <dd class="SMWP_property_value"><a href="$link" title="Property:$name">$name</a></dd>
    <dt class="SMWP_property">Type:</dt>
        <dd class="SMWP_property_value">$type ($required)</dd>
</dl>
EOT;
        return $parser->insertStripItem( $output, $parser->mStripState );
    }
    
    /**
    *   Function to detect and extract the properties definitio from a text
    *
    * @param $text String the text to be parsed
    * @return $properties Array containing the properies infered
    */
    public function extractProperties($text){
        $ma = array();
        $matchs = preg_match_all($this->preg,$text,$ma);

        $properties = array();
        foreach($ma[0] as $key => $match){
            $properties[strtolower($ma[1][$key])] = array(
                isset($ma[1][$key])? $ma[1][$key] : '',
                isset($ma[2][$key])? $ma[2][$key] : '',
                isset($ma[3][$key])? $ma[3][$key] : ''
                );
        }
        return $properties;
    }
    
}